<?php
/*
 * @Author: 杨红兵 
 * @Date: 2022-07-13 16:43:13 
 * @Last Modified by: 杨红兵
 * @Last Modified time: 2022-07-13 17:30:19
 */

namespace app\libraries\utils\validate;

use app\constdir\SysErrorCode;
use app\libraries\exception\ApiException;
use think\Validate;
use Throwable;

trait ValidatesWhenResolvedTrait
{
    /**
     * 调用验证
     * @throws ApiException
     */
    public function validateResolved()
    {
        $action = $this->action();

        $rules = $this->getRule()[$action] ?? [];
        $rules = array_merge($this->getcommonRules(), $rules);
        $msgs = array_merge($this->commonMsg, $this->msgs);

        if (!empty($rules)) {
            $this->validate($this->all(), $rules, $msgs);
        }
    }

    /**
     * 获取验证规则
     * @return mixed
     */
    protected function getRule()
    {
        return $this->rules;
    }

    /**
     * 获取公共验证规则
     * @return mixed
     */
    protected function getcommonRules()
    {
        return $this->commonRules;
    }

    /**
     * 验证数据
     * @param array $data
     * @param $validate
     * @param array $message
     * @param bool $batch
     * @return bool
     * @throws ApiException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false): bool
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        try {
            return $v->failException(true)->check($data);
        } catch (Throwable $ex) {
            throwException(SysErrorCode::SYS_PARAMS_ERROR, $ex->getMessage());
        }

        return false;
    }
}